//
//  JGHomeController.swift
//  JGWB
//
//  Created by 付建国 on 2016/10/9.
//  Copyright © 2016年 sher. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class JGHomeController: BaseController {
    
    // MARK:- 自定义属性
    
    
    // MARK:- 懒加载属性
    fileprivate lazy var titleView : TitleButton = TitleButton()
    fileprivate lazy var backView : UIView = UIView()
    // 注意：在闭包中如果使用当前对象的属性或者调用方法，也需要加self
    // 两个地方需要使用self：1.如果函数中出现歧义 2.闭包中使用当前对象的属性和方法
    fileprivate lazy var popoverAnimator : PopoverAnimator = PopoverAnimator.init {[weak self] (presented) in
        self?.titleView.isSelected = presented
    }
    
    fileprivate lazy var statusModel : [StatusViewModel] = [StatusViewModel]()
    fileprivate lazy var tipLabel : UILabel = UILabel()
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        visitorView.addRotationAnim()
        //1.没有登录时设置的内容
        if !isLogin {
            return
        }
        
        //2.设置导航栏的内容
        setupNavgationBar()
        
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300
        
        //        refreshControl = UIRefreshControl()(系统刷新)
        setupHeaderView()
        setupFooderView()
        setupTipLabel()
        
    }
}

// MARK:- 设置UI界面
extension JGHomeController{
    fileprivate func setupNavgationBar(){
        //左边的item
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(imageName: "navigationbar_friendattention")
        
        //右边的item
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(imageName: "navigationbar_pop")
        
        //设置titleView
        titleView.setTitle(PersonViewModel.shareIntance.account?.screen_name, for: .normal)
        navigationItem.titleView = titleView
        titleView.addTarget(self, action: #selector(titleBtnClick(_:)), for: .touchUpInside)
    }
    
    fileprivate func setupHeaderView(){
        let header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadNewStatues))
        
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("释放更新", for: .pulling)
        header?.setTitle("加载中...", for: .refreshing)
        
        tableView.mj_header = header
        tableView.mj_header.beginRefreshing()
    }
    
    fileprivate func setupFooderView(){
        tableView.mj_footer = MJRefreshAutoFooter.init(refreshingTarget: self, refreshingAction: #selector(loadMoreStatues))
    }
    
    fileprivate func setupTipLabel(){
        
        backView.frame = CGRect.init(x: 0, y: -20, width: UIScreen.main.bounds.width, height: 64)
        backView.backgroundColor = UIColor.white
        navigationController?.navigationBar.insertSubview(backView , at: 0)
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
        tipLabel.frame = CGRect.init(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32)
        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor = UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: 15)
        tipLabel.textAlignment = .center
        tipLabel.isHidden = true
    }
}

// MARK:- 监听事件点击
extension JGHomeController {
    @objc fileprivate func titleBtnClick(_ titleView : TitleButton){
        
        //弹出控制器
        let popoverVc = PopoverController()
        //设置弹出样式(.custom 模态后 之前页面不会被移除)
        popoverVc.modalPresentationStyle = .custom
        
        //设置转场的代理
        popoverVc.transitioningDelegate = popoverAnimator
        
        popoverAnimator.presentedFrame = CGRect.init(x: (view.frame.size.width - 180) * 0.5, y: 60, width: 180, height: 250)
        
        present(popoverVc, animated: true, completion: nil)
    }
}

// MARK:- 请求数据
extension JGHomeController{
    
    /// 加载最新数据
    @objc fileprivate func loadNewStatues(){
        loadStatuses(isNewData: true)
    }
    // 加载更多数据
    @objc fileprivate func loadMoreStatues(){
        loadStatuses(isNewData: false)
    }
    
    fileprivate func loadStatuses(isNewData : Bool){
        
        //获取since_id //获取max_id
        var since_id = 0
        var max_id = 0
        if isNewData{
            since_id = self.statusModel.first?.status?.mid ?? 0
        }else{
            max_id = self.statusModel.last?.status?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id - 1)
        }
        
        NetworkTools.shareInstance.loadStatuses(since_id: since_id, max_id : max_id) { (result, error) in
            
            if error != nil{
                print(error)
                return
            }
            
            guard let resultArray = result else{
                return
            }
            
            var tempStatusModel = [StatusViewModel]()
            for statusDict in resultArray{
                
                let status = Status.init(dict: statusDict)
                let viewModel = StatusViewModel.init(status: status)
                tempStatusModel.append(viewModel)
            }
            
            if isNewData {
                self.statusModel = tempStatusModel + self.statusModel
            }else{
                self.statusModel += tempStatusModel
            }
            
            
            //缓存图片
            self.cacheImages(viewModels: tempStatusModel)
        }
    }
    
    fileprivate func cacheImages(viewModels
        : [StatusViewModel]){
        //创建group
        let group = DispatchGroup.init()
        
        //缓存图片
        for viewModel in viewModels {
            for picURL in viewModel.picURLs {
                group.enter()
                SDWebImageManager.shared().downloadImage(with: picURL, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    group.leave()
                })
            }
        }
        //刷新表格
        group.notify(queue: DispatchQueue.main) {
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            //显示提示label
            self.showTipLabel(count: viewModels.count)
            
        }
    }
    //显示提示的Label
    fileprivate func showTipLabel(count : Int){
        tipLabel.text = count == 0 ? "没有新数据" : "\(count)条新微博"
        
        //添加动画
        UIView.animate(withDuration: 1.0, animations: {
            
            self.tipLabel.isHidden = false
            self.tipLabel.frame.origin.y = 44
            
            }) { (_) in
                
            UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: {
                
                 self.tipLabel.frame.origin.y = 10
                
                }, completion: { (_) in
                    
                 self.tipLabel.isHidden = true
            })
                
        }
    }

}

// MARK:- tableview的数据源和协议方法
extension JGHomeController{
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusModel.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell")! as! JGHomeViewCell
        
        let viewModel = statusModel[indexPath.row]
        
        cell.viewModel = viewModel
        
        return cell
    }
    
    //不使用自动计算高度(需要删除到底部的约束和注释自动计算代码)
    //    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    //        let viewModel = statusModel[indexPath.row]
    //        return viewModel.cellHeight
    //    }
    
}





















